/*
 *文件名： MongoDbDaoImpl.java
 *版权： Copyright by 云天励飞 intellif.com
 *描述： Description
 *创建人：mozping
 *创建时间： 2018/9/19 12:20
 *修改理由：
 *修改内容：
 */
package indi.mozping.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import indi.mozping.dbpool.MongoDbUtil;
import indi.mozping.utils.MongodbUtil;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author mozping
 * @version 1.0
 * @date 2018/9/19 12:20
 * @see MongoDbDaoImpl
 * @since JDK1.8
 */
@Repository
public class MongoDbDaoImpl {

    private static final Logger LOG = LoggerFactory.getLogger(MongoDbDaoImpl.class);

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    MongoDbUtil mongoDbUtil;

    public JSONObject insert(List<Document> list) throws Exception {
        //使用insertMany插入多条数据
        MongoCollection coll = mongoDbUtil.getCollection("testxn");
        try {
            coll.insertMany(list);
        } catch (Exception e) {
            throw e;
        }
        LOG.info("新增数据成功!");
        return null;
    }

    public JSONObject insert(List<Document> list, String tableName) throws Exception {
        //使用insertMany插入多条数据
        MongoCollection coll = mongoDbUtil.getCollection(tableName);
        try {
            LOG.info("Dao 层插入开始...");
            coll.insertMany(list);
            LOG.info("Dao 层插入成功...");
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    public JSONObject insert(Document doc, String tableName) throws Exception {
        //使用insertMany插入多条数据
        MongoCollection coll = mongoDbUtil.getCollection(tableName);
        try {
            coll.insertOne(doc);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    public JSONArray query(BasicDBObject condition, int skip, int limit, String table, BasicDBObject sort) {

        MongoCollection coll = mongoDbUtil.getCollection(table);
        long begin = System.currentTimeMillis();
        LOG.info(coll.toString());
        FindIterable<Document> res = coll.find(condition).skip(skip).sort(sort).limit(limit);

        JSONArray retArray = MongodbUtil.documentIterableToJsonArray(res);
        System.out.println("查询数据库消耗时间：" + (System.currentTimeMillis() - begin) + "ms");
        return retArray;
    }


    public long count(String tableName) {
        MongoCollection coll = mongoDbUtil.getCollection(tableName);
        return coll.count();
    }
}